package cn.itcast.com.Annotation.process;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class StudentFactory {
    private Class targetclass;


    public Student getStudent(int initAge,String initName) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        targetclass = Student.class;
        judgeAge(initAge);
        judgeName(initName);
        Constructor declaredConstructor = targetclass.getDeclaredConstructor(String.class, int.class);
        declaredConstructor.setAccessible(true);
        Student st = (Student) declaredConstructor.newInstance(initName,initAge);

        return null;
    }

    private void judgeAge(int initAge) throws NoSuchFieldException {
        Field age = targetclass.getDeclaredField("age");
        //判断该属性是否有注解约束
        if(age.isAnnotationPresent(AgeConstraint.class)){
            int maxAge = age.getAnnotation(AgeConstraint.class).maxAge();
            int minAge = age.getAnnotation(AgeConstraint.class).minAge();
            if (initAge > maxAge || initAge < minAge){
                throw new IllegalArgumentException("参数非法，年龄");
            }
        }
    }

    public void judgeName(String initName) throws NoSuchFieldException {
        Field name = targetclass.getDeclaredField("name");
        if (name.isAnnotationPresent(NameLengthConstraint.class)){
            int lengthLimit = name.getAnnotation(NameLengthConstraint.class).lengthLimit();
            if (lengthLimit > 5){
                throw new IllegalArgumentException("参数非法，名字");
            }
        }
    }
}
